#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>


int main(int argc, char const *argv[])
{
    int num=3;
    pid_t pid;
    int i;
    for (i = 0; i < num; i++)
    {
        // if ((pid = fork()) == -1)
        // {
        //     perror("fork error");
        //     exit(1);
        // }
        pid = fork();
        if(pid == 0)
        {
            break;
        }
    }
    if (i==0)
    {
        execlp("ps", "ps", "aux", NULL);
        perror("failed");
        exit(1);
    }
    if (i == 1)
    {
        execl("./test.out", "aaa", NULL);
        perror("exec fail");
        exit(1);
    }
    if (i == 2)
    {
        execl("./error.out", "aaa", NULL);
        perror("exec fail");
        exit(1);
    }
    if(i==3)
    {
        int status;
        pid_t wait_pid;
        while((wait_pid == waitpid(-1, status, WNOHANG)) != -1)
        // while((wait_pid == wait(&status)) != -1)
        {
            printf("--------- child died pid = %d\n", wait_pid);
            if(WIFEXITED(status))
            {
                printf("return value %d\n", WEXITSTATUS(status));
            }
            else if (WIFSIGNALED(status))
            {
                printf("died by signal: %d\n", WTERMSIG(status));
            }
        }
    }
    
    return 0;
}